package com.liang.utils;

import org.apache.commons.lang.StringUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SentDateTerm;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * @ClassName EmailUtils
 * @Description TODO
 * @Author liang
 * @Date 2019/4/9 23:05
 * @Version 1.0
 **/
public class EmailUtils {
    private static String PROTOCOL = "imap";
    private static String HOST = "mail.servyou.com.cn";
    private static int PORT = -1;
    private static String FILE = "INBOX";



    public static String[][]  readEmail(String username,String password,Date startTime,Date endTime) throws Exception {
        URLName URL = new URLName(PROTOCOL, HOST, PORT, FILE, username, password);
        Store store ;
        Folder folder ;
        Message[] messages ;

        //对发件时间进行筛选
        SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE,  startTime );
        SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE,  endTime);
        SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);

        try {
            store = Session.getInstance(new Properties(), null).getStore(URL);
        } catch (Exception e) {
            throw new Exception("连接错误!");
        }
        try {
            store.connect();
            folder = store.getFolder(URL);
            folder.open(Folder.READ_WRITE);
            messages = folder.search(comparisonAndTerm);
        } catch (Exception e) {
            throw new Exception("用户名或密码错误!");
        }


        try {
            String[][] message = parseMessage(messages);
            // 5、关闭
            folder.close(false);
            store.close();
            return message;
        } catch (Exception e) {
            throw new Exception("此日期范围内无邮件");
        }


    }

    private static String[][]  parseMessage(Message... messages) throws Exception {
        int size = messages.length;
        if (messages == null || size < 1)
            throw new Exception();
        String[][] tableData  = new String[size][6];
        //根据登录用户名,找到对应的姓名,维护一个中英文对照文件
        String xm = PropertiesUtils.getValue(PropertiesUtils.getValue("username"));
        // 解析所有邮件
        for (int i = 0, count = size; i < count; i++) {
            MimeMessage msg = (MimeMessage) messages[i];
            String subject = msg.getSubject();
            //发件人姓名
            InternetAddress sender = (InternetAddress) msg.getFrom()[0];
            String senderName = parseName(sender.getPersonal());

            Date sentDate = msg.getSentDate();//发送日期
            String date = TimeUtils.dateToString(sentDate);

            int xh = i+1 ;//序号
            String[] data = {date, xm,String.valueOf(xh),senderName,subject,"无需处理",""};
           tableData[i]=data;
        }
        return tableData;

    }

    /**
     * 解析邮件中名字,防止乱码
     * @param name
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String parseName(String name) throws UnsupportedEncodingException {
        String getName = StringUtils.defaultIfEmpty(name, StringUtils.EMPTY);//可能信件中没有传递用户名
        String myName = MimeUtility.decodeText(getName);//(符合RFC2047规范)解密
        return myName;
    }
}
